const { SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS } = require('constants');
var request= require('request');
const Influx = require('influx'); //导包
const { nextTick } = require('process');
// 定义数据库连接和数据格式，创建client
console.log('start request data ...');
async function doPerf(datas) { 
    await influx.writePoints(datas).catch(
        (err) =>{ logger.log('write error', err); }
    );
};

 function doWrite(datas,onPost){
    var client = new Influx.InfluxDB({
      database: 'mydb',
      username: 'root',
      password: 'root',
      hosts: [{ host: '10.205.21.19' }]
    });
    var index =0;
    var postData = function(){
        var next = function(){
            index++;
            postData();

        }
        if(index< datas.length){
            var item = datas[index];
            var url = "http://10.205.21.19:8086/write?db=mydb&u=root&p=root";
            var body="T_"+item.tags.key;
            var body="T_Real";
            for( p in item.tags){
                body+=","+p+"="+item.tags[p];
            }
            body += " rtd="+item.fields.rtd.toString();
            //var t = (item.time+8*24*3600*1000)*1000000
            var t = item.time.substr(0,19)+".nnnnnnnnnZ";
            var t = ((new Date(item.time)).getTime()+8*3600*1000)*1000000;
            body += " "+t.toString();

            request({
                url:url,
                method: "POST",
                body:body

            }, function(err, response, body){
                if( err && err!=null){
                    console.log(err);
                }
                index ++;
                postData();

            })
 
        }
        else{
            client.pool = null;
            client = null;
            onPost();
        }
    }
    postData(); 
}

function getDatas(onGet){
    var url = "http://10.201.35.30:8090/enviSensor/selectByCompanyName";
    var token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG1pbiJ9.izglxuahSQb5by40gXqT1IcVbhmZQsE8cBu4X8tZKM0";
    request({
        url:url ,
        method: "GET",
        json: true,
        headers: {
            "token": token,
        }
    }, function(error, response, body){
        try{
            if( !error && response.statusCode == 200){
                var datas =[];
                if( body.errcode==0){
                    var datas=[];
                    body.data.array.forEach(item => {
                        var pm10={
                            measurement: 'T_Real',
                            //time: (new Date(item.pm10Time)).getTime() ,
                            time: item.pm10Time,
                            tags: {
                              dk:'pm10',
                              type: item.type.toString() ,
                              label: item.label.replace(/\ +/g,"") ,
                              factory: item.factory
                            },
                            fields : {
                                rtd: item.pm10Rtd
                            }
                        };
                        datas.push(pm10);
                        var pm25={
                            measurement: 'T_Real',
                            //time: (new Date(item.pm25Time)).getTime() ,
                            time: item.pm25Time ,
                            fields: {
                                rtd: item.pm25Rtd
                            },
                            tags: {
                              dk:'pm25',
                              type: item.type ,
                              label: item.label,
                              factory: item.factory
                            }
                        };
                        datas.push(pm25);
                        var tsp={
                            measurement: 'T_Real',
                            //time: (new Date(item.tspTime)).getTime() ,
                            time: item.tspTime,
                            fields: {
                                rtd: item.tspRtd
                            },
                            tags: {
                              dk:'tsp',
                              type: item.type ,
                              label: item.label,
                              factory: item.factory
                            }
                        };
                        datas.push(tsp);
                        var voc={
                            measurement: 'T_Real',
                            //time: (new Date(item.vocTime)).getTime() ,
                            time: item.vocTime ,
                            fields: {
                                rtd: item.vocRtd
                            },
                            tags: {
                              dk:'voc',
                              type: item.type ,
                              label: item.label,
                              factory: item.factory
                            }
                        };
                        datas.push(voc);
                    });
                    doWrite(datas, function(){
                        console.log('post data:', datas.length);
                    });
                }
                console.log(datas);
            }
            if( onGet){
                onGet();
            }
        }
        catch(er){
            console.log(er)
        }
    });
}

function load(){
    setTimeout(() => {
        getDatas(function(){
            load();
        });
    }, 1000*5 );
}

load();